package org.jeecg.modules.demo.soFyft.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.demo.cwSaleInvoice.entity.CwSaleInvoice;
import org.jeecg.modules.demo.cwSaleInvoice.mapper.CwSaleInvoiceMapper;
import org.jeecg.modules.demo.soFeiyong.entity.SoFeiyong;
import org.jeecg.modules.demo.soFeiyong.mapper.SoFeiyongMapper;
import org.jeecg.modules.demo.soFyft.entity.SoFyft;
import org.jeecg.modules.demo.soFyft.mapper.SoFyftMapper;
import org.jeecg.modules.demo.soFyft.service.ISoFyftService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @Description: so_fyft
 * @Author: jeecg-boot
 * @Date: 2022-01-18
 * @Version: V1.0
 */
@Service
public class SoFyftServiceImpl extends ServiceImpl<SoFyftMapper, SoFyft> implements ISoFyftService {

    @Resource
    private SoFyftMapper soFyftMapper;
    @Resource
    private CwSaleInvoiceMapper cwSaleInvoiceMapper;
    @Resource
    private SoFeiyongMapper soFeiyongMapper;


    @Override
    public SoFeiyong getByfyNo(String soFyNo) {
        return soFyftMapper.getByfyNo(soFyNo);
    }

    @Override
    @Transactional
    public boolean deleteFyft(SoFyft soFyft) {
        try {
            CwSaleInvoice cw = cwSaleInvoiceMapper.getByInvoiceNo(soFyft.getFpNo());
            cw.setFtJine(cw.getFtJine().subtract(soFyft.getFtJine()));
            cwSaleInvoiceMapper.updateById(cw);

            SoFeiyong sf = soFeiyongMapper.getBySoFyNo(soFyft.getSoFyNo());
            sf.setFpNo("");
            sf.setSyFtjine(sf.getSyFtjine().add(soFyft.getFtJine()));
            if (sf.getSyFtjine().compareTo(BigDecimal.valueOf(0)) < 1) {  //剩余分摊金额<=0
                sf.setIsFt(2);
            } else {
                if (sf.getSyFtjine().compareTo(sf.getTaxamount()) == -1) {  //剩余分摊金额<分摊总金额
                    sf.setIsFt(1);
                } else {
                    sf.setIsFt(0);
                }
            }
            soFeiyongMapper.updateById(sf);
            soFyftMapper.deleteById(soFyft);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }
}
